<?php
/**
 * File: ServiceController.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/18 19:32
 */

namespace Home\Controller;

use Common\Service\Address;
use Common\Service\Attachment;
use Common\Service\User;
use Think\Upload;

/**
 * 服务类
 * Class ServiceController
 * @package Home\Controller
 */
class ServiceController extends BaseController
{
    protected function _initialize()
    {
        $this->notAuthActions = ['jump', 'auth', 'address'];
        parent::_initialize();
    }

    /**
     * ！测试
     */
    public function test()
    {
        $msgParam['user_id'] = 3;
        $msgParam['id'] = 1;
        notification('check', 'apply', $msgParam);
    }

    /**
     * 附件上传接口
     * @desc ajax-post 可上传多个（ajaxfileupload）
     * @return int [].id 附件id
     * @return int [].name 附件名称
     * @return int [].path 附件路径
     * @request /service/upload
     */
    public function upload()
    {
        //TODO 上传大文件限制 https://segmentfault.com/a/1190000002670683
        //上传参数
        $config = array(
//            'maxSize'    =>    3145728,
            'rootPath' => UPLOAD_PATH,
            'saveName' => array('generate_random_filename', 'NTYK'),
            'autoSub' => true,
            'subName' => array('date', 'Ym'),
        );
        $upload = new Upload($config);
        if (IS_POST) {
            $files = $upload->upload();
            if (!$files) {
                // 提示错误信息
                $this->jsonFail($upload->getError());
            } else {
                //存储附件信息
                $service = Attachment::instance();
                $serial = $service->saveAttachment($files);
                if (!$serial) {
                    return $this->jsonFail($service->error);
                }
                $attachments = M('attachment')
                    ->where(['serial' => $serial])
                    ->field('id,name,path')
                    ->select();
                return $this->jsonSuccess($attachments);
            }
        } else {
            return $this->jsonFail('请求方式错误');
        }
    }

    /**
     * url附件上传接口
     * @desc ajax-post
     * @param array $urls url路径数组
     * @return int [].id 附件id
     * @return int [].name 附件名称
     * @return int [].path 附件路径
     * @request /service/uploadUrl
     */
    public function uploadUrl()
    {
        $urls = $_POST['urls'];
        if (empty($urls) || !is_array($urls)) {
            return $this->jsonFail('url不能为空');
        }
        foreach ($urls as $url) {
            //超级无敌牛B的url正则
            $reg = '@(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))@';
            if (!preg_match($reg, $url)) {
                return $this->jsonFail('url格式错误');
            }
        }
        $service = Attachment::instance();
        $serial = $service->saveUrlAttachment($urls);
        if (!$serial) {
            return $this->jsonFail($service->error);
        }
        $attachments = M('attachment')
            ->where(['serial' => $serial])
            ->field('id,name,path')
            ->select();
        return $this->jsonSuccess($attachments);

    }

    /**
     * 钉钉pc端跳转页面
     */
    public function jump()
    {
        $jumpUrl = (U('auth', '', false, true));
        $this->assign('corpId', C('DINGTALK.CorpId'));
        $this->assign('jumpUrl', $jumpUrl);
        $this->display('common/jump');
    }

    /**
     * 钉钉用户登录
     * @param string $callback 回调地址
     * @return mixed
     */
    public function auth($callback = '/')
    {
        //判断是否已经登录
        $user = $this->authenticate();
        if ($user) {
            //已经登录直接跳转
            $can = true;
        } else {
            //未登录验证钉钉
            $can = $this->validateUserId();
        }
        if ($can) {
            redirect(urldecode($callback));
        }
        $this->fail('未登录或登录过期，请重新登录后访问');
    }

    /**
     * 验证钉钉code
     * @return bool
     */
    protected function validateUserId()
    {

        $code = I('get.code');
        if (empty($code)) {
            return false;
        }
        $res = dingtalk()->getUserId($code);
        $userService = User::instance();
        $userIdentity = $userService->getUserByUserId($res['userid']);
        //用户存在
        if ($userIdentity) {
            //登录
            $userService->login($userIdentity['id']);
            return true;

        }
        return false;
    }

    /**
     * 获取地区表
     * @desc ajax-get
     * @param int $id 上级地区id|no|0或空表示全国
     * @return int [].id 地区id
     * @return int [].name 地区名称
     * @request /service/address
     */
    public function address($id = 0)
    {
        $service = Address::instance();
        $result = $service->getAddress($id);
        return $this->jsonSuccess($result);
    }
}
